package flexconsole.controller {
	import air.update.ApplicationUpdaterUI;
	import air.update.events.UpdateEvent;
	
	import flash.events.ErrorEvent;
	
	import flexconsole.AppFacade;
	import flexconsole.ConfigKeys;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	import mx.utils.StringUtil;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;
	
	/**
	 * Command that checks for application updates.
	 *
	 * @author ivanchoo
	 *
	 */
	public class CheckAppUpdateCommand extends SimpleCommand {
		
		static public const UPDATE_URL:String = 'https://flex-console.googlecode.com/svn/releases/update.xml';
		
		static private var logger:ILogger = Log.getLogger("flexconsole.controller.CheckAppUpdateCommand");
		
		static private var _updater:ApplicationUpdaterUI;
		
		static private var instance:CheckAppUpdateCommand;
		
		private var isInitialized:Boolean = false;
		
		private var isChecking:Boolean = false;
		
		/**
		 * Singleton instance of the <code>ApplicationUpdaterUI</code>.
		 * @return
		 *
		 */
		public function get updater():ApplicationUpdaterUI {
			if (_updater == null) {
				_updater = new ApplicationUpdaterUI();
				_updater.updateURL = UPDATE_URL;
				_updater.addEventListener(UpdateEvent.INITIALIZED, onUpdateEvent);
				_updater.addEventListener(UpdateEvent.CHECK_FOR_UPDATE, onUpdateEvent);
				_updater.addEventListener(ErrorEvent.ERROR, onErrorEvent);
				_updater.isCheckForUpdateVisible = false;
				_updater.isFileUpdateVisible = true;
				_updater.isInstallUpdateVisible = true;
				_updater.isDownloadProgressVisible = true;
				_updater.isDownloadUpdateVisible = true;
			}
			return _updater;
		}
		
		/**
		 * Checks for updates now.
		 *
		 */
		public function checkNow():void {
			logger.debug("checkNow()");
			
			if (isChecking) {
				logger.warn("Already checking for updates, ignoring current call");
				return;
			}
			
			var appFacade:AppFacade = facade as AppFacade;
			
			appFacade.configProxy.setValue(ConfigKeys.CHECK_UPDATE_STATUS, appFacade.resourceBundle.checkingAppUpdate);
			
			if (!isInitialized) {
				isInitialized = true;
				updater.initialize();
			} else {
				updater.checkNow();
			}
		}
		
		private function onUpdateEvent(event:UpdateEvent):void {
			logger.debug("onUpdateEvent({0})", event);
			
			if (event.type == UpdateEvent.INITIALIZED) {
				updater.checkNow();
			} else if (event.type == UpdateEvent.CHECK_FOR_UPDATE) {
				updateStatus();
			}
		}
		
		private function onErrorEvent(event:ErrorEvent):void {
			logger.debug("onErrorEvent({0})", event);
			logger.warn(event.text);
			updateStatus();
			//  log? or Ignore?
		}
		
		private function updateStatus():void {
			var appFacade:AppFacade = facade as AppFacade;
			appFacade.configProxy.setValue(ConfigKeys.CHECK_UPDATE_STATUS, StringUtil.substitute(appFacade.resourceBundle.lastCheckAppUpdate, new Date().toLocaleString()));
		}
		
		override public function execute(notification:INotification):void {
			logger.debug("execute({0})", notification);
			super.execute(notification);
			
			//   Shutdown sequence
			try {
				logger.debug("Initializing ApplicationUpdaterUI with URL {0}", UPDATE_URL);
				
				if (!instance) {
					instance = this;
				}
				instance.checkNow();
				
			} catch (e:Error) {
				logger.error(e.message);
			}
		}
	
	
	}
}